package com.example.gsq.news.base;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;

import com.example.gsq.news.util.C;
import com.example.gsq.news.util.HttpUtil;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BaseTaskPool {

    private static ExecutorService mTaskPool;

    private BaseHandler mHandler;

    public BaseTaskPool(BaseHandler handler) {
        mTaskPool = Executors.newCachedThreadPool();
        mHandler = handler;
    }

    public void addTask(int taskId, int taskType, String urlString) {
        mTaskPool.execute(new HttpTaskThread(taskId, taskType, urlString, null));
    }

    public void addTask(int taskId, int taskType, String urlString, HashMap<String, String> param) {
        mTaskPool.execute(new HttpTaskThread(taskId, taskType, urlString, param));
    }

    private class HttpTaskThread implements Runnable {
        private String urlString = null;
        private HashMap<String, String> param = null;
        private int taskId;
        private int taskType;

        public HttpTaskThread(int taskId, int taskType, String urlString, HashMap<String, String> param) {
            this.urlString = urlString;
            this.param = param;
            this.taskId = taskId;
            this.taskType = taskType;
        }

        @Override
        public void run() {
            Message message = new Message();
            Bundle bundle = new Bundle();
            switch (taskId) {
                case C.TaskId.ACTIVITY_GET_JSON_LIST:
                case C.TaskId.FRAGMENT_GET_JSON_LIST:
                    String responseString = HttpUtil.getJSONString(urlString);
                    bundle.putInt("TaskId", taskId);
                    bundle.putInt("TaskType", taskType);
                    bundle.putString("response", responseString);
                    message.setData(bundle);
                    message.what = C.TaskStatus.TASK_COMPLETE;
                    mHandler.sendMessage(message);
                    break;
                case C.TaskId.ACTIVITY_GET_ITEM_BITMAP:
                case C.TaskId.FRAGMENT_GET_ITEM_BITMAP:
                    Bitmap bitmap = HttpUtil.getBitmap(urlString);
                    bundle.putInt("TaskId", taskId);
                    bundle.putInt("TaskType", taskType);
                    bundle.putString("imageUrl", urlString);
                    message.setData(bundle);
                    message.obj = bitmap;
                    message.what = C.TaskStatus.TASK_COMPLETE;
                    mHandler.sendMessage(message);
                    break;
            }
        }
    }
}
